package com.gzj.mall.product.service.impl;

import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gzj.common.utils.PageUtils;
import com.gzj.common.utils.Query;

import com.gzj.mall.product.dao.CategoryDao;
import com.gzj.mall.product.entity.CategoryEntity;
import com.gzj.mall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> queryCategoryTree() {
        //1.所有的分类信息
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);

        //2.获取父级分类信息
        List<CategoryEntity> categoryEntityList = categoryEntities.stream().filter(categoryEntity -> categoryEntity.getParentCid() == 0)
                .map(categoryEntity -> {
                    categoryEntity.setCategoryEntitySons(getCategoryEntitySon(categoryEntity, categoryEntities));
                    return categoryEntity;
                })
                .sorted(Comparator.comparing(CategoryEntity::getSort))
                .collect(Collectors.toList());

        return categoryEntityList;
    }

    public List<CategoryEntity> getCategoryEntitySon(CategoryEntity categoryEntity, List<CategoryEntity> categoryEntityList) {
        return categoryEntityList.stream().filter(categoryEntityTree -> categoryEntityTree.getParentCid().equals(categoryEntity.getCatId()) )
                .sorted((k1,k2) ->k1.getSort()==null ? 0 : k1.getSort() - (k2.getSort() == null ? 0 : k2.getSort()))
                .map(categoryEntityTree -> {
                    categoryEntityTree.setCategoryEntitySons(getCategoryEntitySon(categoryEntityTree, categoryEntityList));
                    return categoryEntityTree;
                }).collect(Collectors.toList());
    }
}